<?php

namespace App\Wxapp\Controllers;

use App\Jobs\CouponCodeRollback;
use App\Store\Models\Wxapp\WxappCoupon;
use App\Store\Models\Wxapp\WxappCouponCodeList;
use App\Store\Models\Wxapp\WxappSetting;
use App\Store\Services\Wxcoupon\Wxcoupon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * 优惠券
 */
class CouponController extends BaseController
{


    public function getcouponinfo(Request $request){
        $id=intval($request->id);
        $info=WxappCoupon::where(['cp_id' => $this->cp_id,'is_del'=>1,'id'=>$id])->where([['available_begin_time','<=',time()],['available_end_time','>=',time()]])
        ->select(['id','img_path','stock_name','goods_name','stock_type','discount_amount','discount_percent','transaction_minimum','max_coupons_per_user','coupon_code_count'])
        ->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '优惠券不存在']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info'=>$info]]);
    }

    protected function sendcouponcode($info){
        //发放code
        $coupon_code_list=[date('Ym').$this->cp_id.$this->meminfo['id'].date('YmdHis')];
        $upload_request_no=date('Ym').$this->cp_id.$this->meminfo['id'].time();

        $Wxcoupon=new Wxcoupon($this->cp_id);
        $res=$Wxcoupon->import($coupon_code_list,$upload_request_no,$info->stock_id);
        Log::info('优惠券生成结果',$res);
        if($res['code']=='000'){
            WxappCouponCodeList::create([
                'cp_id'=>$this->cp_id,
                'store_ids'=>$info->store_ids,
                // 'goods_category_ids'=>$info->goods_category_ids,
                'coupon_id'=>$info->id,
                'stock_id'=>$info->stock_id,
                'coupon_code'=>$coupon_code_list[0],
                'stock_type'=>$info->stock_type,
                'transaction_minimum'=>$info->transaction_minimum,
                'discount_percent'=>$info->discount_percent,
                'available_end_time'=>$info->available_end_time,
                'discount_amount'=>$info->discount_amount,
                'mem_id'=>$this->meminfo['id']
            ]);



            return $coupon_code_list[0];
        }else{
            return '';
        }








    }


    /**
     * 领取优惠券
     */
    public function getcoupon(Request $request){
        $coupon_id = $request->coupon_id ?? 0;
        $info = WxappCoupon::where(['cp_id' => $this->cp_id,'is_del'=>1,'id'=>$coupon_id])->where([['available_begin_time','<=',time()],['available_end_time','>=',time()]])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '优惠券不存在']);
        }
        $notusecount=WxappCouponCodeList::where(['cp_id' => $this->cp_id,'coupon_id'=>$coupon_id,'mem_id'=>0])->count();
        if($info->coupon_code_count<=($info->send_count-$notusecount)){
            return response()->json(['code' => '001', 'msg' => '优惠券发放次数已达上限']);
        }
        $setting=WxappSetting::where([['cp_id',$this->cp_id]])->first();

        if(!$setting){
            return response()->json(['code' => '001', 'msg' => '无效商户配置']);
        }



        // $sendinfo=WxappCouponCodeList::where(['cp_id' => $this->cp_id,'coupon_id'=>$coupon_id,'coupon_code'=>$coupon_code,'mem_id'=>0])->first();

        // if(!$sendinfo){
        //     return response()->json(['code' => '001', 'msg' => '无效优惠券信息']);
        // }

        //判断领取次数
        $memcount=WxappCouponCodeList::where(['cp_id' => $this->cp_id,'coupon_id'=>$coupon_id,'mem_id'=>$this->meminfo['id'],'is_receive'=>2])->count();

        if($memcount>=$info['max_coupons_per_user']){

            return response()->json(['code' => '001', 'msg' => '领取优惠券超出上限']);
        }

        //获取券码，如库存不存在，则调接口新增券码


        //获取库存中无人使用的券
        $coupon_code_info=WxappCouponCodeList::where(['cp_id' => $this->cp_id,'coupon_id'=>$coupon_id,'mem_id'=>0])->first();

        if($coupon_code_info){
            $coupon_code=$coupon_code_info->coupon_code;

            WxappCouponCodeList::where(['cp_id' => $this->cp_id,'coupon_id'=>$coupon_id,'mem_id'=>0,'id'=>$coupon_code_info->id])->update(['mem_id'=>$this->meminfo['id']]);
            WxappCoupon::where(['cp_id' => $this->cp_id,'is_del'=>1,'id'=>$coupon_id])->increment('send_count',1);
        }else{
            //未获取到，则重新生成
            $coupon_code=$this->sendcouponcode($info);
            if($coupon_code==''){
                return response()->json(['code' => '001', 'msg' => '无效券码']);
            }

            WxappCoupon::where(['cp_id' => $this->cp_id,'is_del'=>1,'id'=>$coupon_id])->increment('send_count',1);
        }
        //加入队列
        CouponCodeRollback::dispatch(['coupon_code'=>$coupon_code,'mem_id'=>$this->meminfo['id']])->delay(now()->addMinutes(15));





        $out_request_no=$coupon_code.mt_rand(1000,9999);
        //发券签名
        $str='coupon_code0='.$coupon_code.'&out_request_no0='.$out_request_no.'&send_coupon_merchant='.$setting->wxpay_mchid.'&stock_id0='.$info->stock_id.'&key='.$setting->wxpay_key;
        $hashstr=strtoupper(hash_hmac("sha256", $str, $setting->wxpay_key));


        $send_coupon_params=[['stock_id'=>$info->stock_id,'out_request_no'=>$out_request_no,'coupon_code'=>$coupon_code]];
        $send_coupon_merchant=$setting->wxpay_mchid;


        return response()->json(['code' => '000', 'msg' => '券码生成成功','data'=>['sign'=>$hashstr,'send_coupon_params'=>$send_coupon_params,'send_coupon_merchant'=>$send_coupon_merchant]]);
    }

    public function getcouponres(Request $request){
        $coupon_id = $request->coupon_id ?? 0;
        $coupon_code = $request->coupon_code ?? '';
        $info = WxappCoupon::where(['cp_id' => $this->cp_id,'is_del'=>1,'id'=>$coupon_id])->where([['available_begin_time','<=',time()],['available_end_time','>=',time()]])->first();
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '优惠券不存在']);
        }
        $sendinfo=WxappCouponCodeList::where(['cp_id' => $this->cp_id,'coupon_id'=>$coupon_id,'coupon_code'=>$coupon_code,'is_receive'=>1,'mem_id'=>$this->meminfo['id']])->first();

        if(!$sendinfo){
            return response()->json(['code' => '001', 'msg' => '无效优惠券信息']);
        }
        WxappCouponCodeList::where(['cp_id' => $this->cp_id,'coupon_id'=>$coupon_id,'coupon_code'=>$coupon_code])
        ->update(['exchange_at'=>time(),'is_receive'=>2]);
        return response()->json(['code' => '000', 'msg' => '领取成功']);
    }




}
